<!--
 * @Author: 关棺 3156298705@qq.com
 * @Date: 2024-12-18 15:21:04
 * @LastEditors: 关棺 3156298705@qq.com
 * @LastEditTime: 2024-12-19 10:35:41
 * @FilePath: \supervision-ui\src\views\file\fileVersion\components\filePreviewDialog.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    @close="handleClose"
    width="80%"
  >
    <el-table :data="fileList" style="width: 100%">
      <el-table-column prop="name" label="文件名"></el-table-column>
      <el-table-column prop="type" label="文件格式"></el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="handleDownload(scope.row)"
            >下载</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script>
export default {
  name: "FilePreviewDialog",
  data() {
    return {
      title: "下载文件列表",
      visible: false,
      fileList: [],
    };
  },
  methods: {
    // 初始化文件列表
    init(arr) {
      console.log(arr);
      this.visible = true;
      this.fileList = arr;
    },
    handleClose() {
      this.visible = false;
    },
    // 处理下载文件的逻辑
    handleDownload(file) {
      if (file.url.endsWith(".pdf")) {
        // 如果是 PDF 文件，强制下载
        fetch(file.url)
          .then((response) => response.blob())
          .then((blob) => {
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url;
            link.download = file.name1 || "download.pdf"; // 设置下载文件的名称
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
          })
          .catch((error) => {
            console.error("下载文件失败:", error);
          });
      } else {
        // 其他文件类型直接下载
        const link = document.createElement("a");
        link.href = file.url;
        link.download = file.name1 || "download"; // 设置下载文件的名称
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },
  },
};
</script>

<style scoped>
/* 自定义样式 */
pre {
  white-space: pre-wrap; /* 自动换行 */
  word-wrap: break-word;
  max-height: 300px;
  overflow-y: auto;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ddd;
}
</style>
